<template>
  <!-- 消息列表 // TODO 使用虚拟列表组件就用不了动画和拖动了 (nyh -> 2024-03-28 06:01:00) -->
  <n-scrollbar ref="msg-scrollbar" style="max-height: calc(100vh - 70px)">
    <!--  右键菜单组件  -->
    <div v-if="conversationList.length > 0" class="p-[4px_10px_0px_8px]">
      <ContextMenu
        v-for="item in conversationList"
        :key="item.conversationID"
        :class="[
          { active: currentConv?.conversationID === item.conversationID },
          { 'bg-[--bg-msg-first-child] rounded-12px relative': item.isPinned }
        ]"
        :data-key="item.conversationID"
        :menu="tencentConversationStore.menuList"
        :special-menu="tencentConversationStore.specialMenuList"
        :content="item"
        class="msg-box w-full h-75px mb-5px"
        @click="handleConvClick(item)"
        @select="$event.click(item)">
        <n-flex :size="10" align="center" class="h-75px pl-6px pr-8px flex-1">
          <n-avatar
            style="border: 1px solid var(--avatar-border-color)"
            :size="44"
            :src="avatar(item)"
            fallback-src="/logo.png"
            round />

          <n-flex class="h-fit flex-1 truncate" justify="space-between" vertical>
            <n-flex :size="4" align="center" class="flex-1 truncate" justify="space-between">
              <n-flex :size="0" align="center" class="leading-tight flex-1 truncate">
                <span class="text-14px leading-tight flex-1 truncate">{{ convName(item) }}</span>
              </n-flex>
              <span
                v-if="item.lastMessage?.type !== TencentCloudChat.TYPES.MSG_CUSTOM"
                class="text text-10px w-fit truncate text-right">
                {{ item.lastMessage?.lastTime ? formatTimestamp(item.lastMessage?.lastTime) : '' }}
              </span>
            </n-flex>

            <n-flex align="center" justify="space-between">
              <div class="text flex-1 leading-tight text-12px truncate" v-html="getLastMessage(item)" />

              <!-- 消息提示 -->
              <n-badge
                :max="99"
                :value="item.unreadCount"
                :color="
                  item.messageRemindType === TYPES.MSG_REMIND_ACPT_AND_NOTE ? 'rgba(128, 128, 128, 0.5)' : undefined
                " />
            </n-flex>
          </n-flex>
        </n-flex>
      </ContextMenu>
    </div>

    <!-- 没有数据显示的提示 -->
    <n-result v-else class="absolute-center" status="418" description="快和朋友聊天吧！">
      <template #footer>
        <n-button secondary type="primary">寻找好友</n-button>
      </template>
    </n-result>
  </n-scrollbar>
</template>
<script lang="ts" setup name="message">
import { useTencentConversationStore } from '@/stores/tencentConversationStore.ts'
import { useTencentConversation } from '@/hooks/useTencentConversation.ts'
import TencentCloudChat, { Conversation } from '@tencentcloud/chat'
import { formatTimestamp } from '@/utils/ComputedTime.ts'
import { useMitt } from '@/hooks/useMitt.ts'
import { MessageEncryptor } from '@/hooks/useMessageEncryptor.ts'
import { MittEnum } from '@/enums'
import { useTauriListener } from '@/hooks/useTauriListener'
import { useCommon } from '@/hooks/useCommon.ts'
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
import { MiaoXinAuditOfficialAccount, MiaoXinSouSouOfficialAccount } from '@/common/tencent.ts'

const appWindow = WebviewWindow.getCurrent()
const { addListener } = useTauriListener()
const { openMsgSession } = useCommon()
// 消息加密
MessageEncryptor.IsEncry = true
const TYPES = TencentCloudChat.TYPES
const tencentConversationStore = useTencentConversationStore()
const tencentConversation = useTencentConversation()
const msgScrollbar = useTemplateRef<HTMLElement>('msg-scrollbar')

const conversationList = computed(() => {
  return tencentConversationStore.conversationList
})
const currentConv = computed(() => tencentConversationStore.currentConv)

const avatar = (item: Conversation) => {
  if (item.type === TYPES.CONV_GROUP) {
    return item.groupProfile.avatar || '/logo.png'
  } else if (item.type === TYPES.CONV_C2C) {
    return item.userProfile.avatar || '/logo.png'
  }

  return 'logo.png'
}

const convName = (item: Conversation) => {
  if (item.type === TYPES.CONV_GROUP) {
    return item.groupProfile.name
  } else if (item.type === TYPES.CONV_C2C) {
    return item.remark || item.userProfile.nick || item.userProfile.userID
  }

  return '系统消息'
}

const getLastMessage = (item: Conversation) => {
  if (item.lastMessage?.type !== TencentCloudChat.TYPES.MSG_CUSTOM) {
    let messageForShow = item.lastMessage?.messageForShow || ''
    if (messageForShow.startsWith(MessageEncryptor.MessageEncryptorContentPrefix)) {
      messageForShow = MessageEncryptor.decrypt(messageForShow)
    }

    if (item.type === TYPES.CONV_GROUP) {
      const fromUser = item.lastMessage?.nameCard || item.lastMessage?.nick || item.lastMessage?.fromAccount
      return `<span class="font-bold">${fromUser}</span>: ${messageForShow}`
    } else {
      if (
        item.lastMessage?.fromAccount === MiaoXinAuditOfficialAccount ||
        item.lastMessage?.fromAccount === MiaoXinSouSouOfficialAccount
      ) {
        const msg = JSON.parse(item.lastMessage?.payload.text)
        return msg.first
      }

      return messageForShow
    }
  }

  return ''
}

const handleConvClick = (item: Conversation) => {
  tencentConversation.handleConvClick(item)
}

watch(
  currentConv,
  (newVal) => {
    console.log('message index current conv', newVal)
    useMitt.emit(MittEnum.LOCATE_SESSION, { conversationID: newVal.conversationID })
  },
  {
    deep: true,
    immediate: true
  }
)

onMounted(() => {
  addListener(
    appWindow.listen(
      'search_to_msg',
      (event: { payload: { info: string; type: 'user' | 'group' | 'conversation' } }) => {
        openMsgSession(event.payload.info, event.payload.type)
      }
    )
  )

  useMitt.on(MittEnum.LOCATE_SESSION, async (e: { conversationID: string }) => {
    const index = conversationList.value.findIndex((item: Conversation) => item.conversationID === e.conversationID)
    if (index !== -1) {
      await nextTick(() => {
        msgScrollbar.value?.scrollTo({
          top: index * (75 + 5) - 264,
          behavior: 'smooth'
        })
      })
    }
  })
})
</script>

<style lang="scss" scoped>
@use '@/styles/scss/message';

#image-no-data {
  @apply size-full mt-60px text-[--text-color] text-14px;
}
</style>
